package com.by.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.easysdk.factory.Factory;
import com.by.bean.AliPay;
import com.by.bean.PayInfo;
import com.by.config.AliPayConfig;
import com.by.service.PayInfoService;
import io.swagger.annotations.Api;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Hzy
 * @version 1.0
 * @date 2025/4/11  11:03
 * @description
 * @since jdk11
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/api")
@Api(tags = "支付宝服务")
@Transactional(rollbackFor = Exception.class)
public class AliPayController {

    @Resource
    AliPayConfig aliPayConfig;
    @Autowired
    PayInfoService payInfoService;


//    @Resource
//    private ShopMapper shopMapper;
    // 支付宝网关URL、格式、字符集、签名类型等配置
    private static final String GATEWAY_URL ="https://openapi-sandbox.dl.alipaydev.com/gateway.do";
    private static final String FORMAT ="JSON";
    private static final String CHARSET ="utf-8";
    private static final String SIGN_TYPE ="RSA2";

    /**
     * 处理前端发起的支付请求，生成支付表单并返回给前端。
     *
     * @param httpResponse 用于直接向客户端响应的HttpServletResponse对象
     * @throws Exception 可能抛出的异常，包括支付宝接口调用异常等
     */
    @GetMapping("/pay") // 前端路径参数格式?subject=xxx&traceNo=xxx&totalAmount=xxx
    public void pay(AliPay aliPay, HttpServletResponse httpResponse) throws Exception {

        // 创建支付宝客户端
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, aliPayConfig.getAppId(),
                aliPayConfig.getAppPrivateKey(), FORMAT, CHARSET, aliPayConfig.getAlipayPublicKey(), SIGN_TYPE);

        // 配置支付请求参数
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setNotifyUrl(aliPayConfig.getNotifyUrl());
        request.setReturnUrl(aliPayConfig.getReturnUrl());
        request.setBizContent("{\"out_trade_no\":\"" + aliPay.getTraceNo() + "\","
                + "\"total_amount\":\"" + aliPay.getTotalAmount() + "\","
                + "\"subject\":\"" + aliPay.getSubject() + "\","
                + "\"timeout_express\":\"15m\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        // 调用支付宝接口，生成支付表单
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        // 将表单直接输出到前端页面
        httpResponse.setContentType("text/html;charset=" + CHARSET);
        httpResponse.getWriter().write(form);
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }

    /**
     * 处理支付宝异步通知请求，验证通知数据并处理支付结果。
     *
     * @param request 包含支付宝回调参数的HttpServletRequest对象
     * @return 返回给支付宝的处理结果字符串
     * @throws Exception 可能抛出的异常，包括数据验证和业务处理异常
     */
    @PostMapping("/notify")  // 注意这里必须是POST接口
    public String payNotify(HttpServletRequest request) throws Exception {
        // 检查交易状态
        String tradeStatus = request.getParameter("trade_status");
        if (tradeStatus != null && tradeStatus.equals("TRADE_SUCCESS")) {
            System.out.println("=========支付宝异步回调========");
            // 收集回调参数
            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
            }

            // 验证支付宝通知的合法性
            if (Factory.Payment.Common().verifyNotify(params)) {
                // 创建PayInfo对象并设置支付信息
                PayInfo payInfo = new PayInfo();
                payInfo.setPay_id(Long.valueOf(params.get("pay_id")));
                payInfo.setUser_id(Long.valueOf(params.get("user_id")));
                payInfo.setOrder_ids(params.get("order_ids"));
                payInfo.setBiz_pay_no(params.get("biz_pay_no"));
                payInfo.setSys_type(Integer.valueOf(params.get("sys_type")));
                payInfo.setPay_status(1); // 假设1表示已支付
                payInfo.setPay_amount(Long.valueOf(params.get("pay_amount")));
                payInfo.setVersion(Integer.valueOf(params.get("version")));
                payInfo.setCallback_content(params.get("callback_content"));
                // 保存支付信息到数据库
                payInfoService.save(payInfo);

            }
        }
        return "success";
    }

}
